<template>
	<el-container>
		<el-aside class="left">
			<left-nav></left-nav>
		</el-aside>
		<el-main class="main">
			<el-container>
				<el-aside class="center">
					<el-tabs v-model="activeName" @tab-click="handleClick">
						<el-tab-pane label="点餐" name="first">
							<el-table :data="tableData" style="width: 100%">
								<el-table-column prop="goodsName" label="商品">
								</el-table-column>
								<el-table-column prop="count" label="数量" width="80px">
								</el-table-column>
								<el-table-column prop="price" label="价格" width="80px">
								</el-table-column>
								<el-table-column fixed="right" label="操作" width="80px">
									<template slot-scope="scope">
										<el-button @click.native.prevent="deleteRow(scope.row)" type="text"
											size="small">
											移除
										</el-button>
									</template>
								</el-table-column>
							</el-table>
							<div class="SummaryTotal">
								数量：{{totalCount}} 总价：{{totalMoney}}
							</div>
							<div class="btns">
								<el-button type="warning" round @click="clearData">清空</el-button>
								<el-button type="success" round @click="checkOut">结账</el-button>
							</div>
						</el-tab-pane>
						<el-tab-pane label="订单列表" name="second">
							<ul class="historyOrderList">
								<li v-for="(item) in historyOrderList" :key="item._id">
									<div class="hd"><span class="orderid">订单编号:{{item._id}}</span><span
											class="money">订单金额:{{item.ordertotal}}元</span></div>
									<table>
										<tr class="row-title">
											<th>商品名称</th>
											<th>商品数量</th>
											<th>商品价格</th>
										</tr>
										<tr class="row-cols" v-for="(list,index) in item.orderlist" :key="index">
											<td>{{list.goodsName}}</td>
											<td>{{list.count}}</td>
											<td>{{list.price}}</td>
										</tr>
									</table>
								</li>
							</ul>
						</el-tab-pane>
					</el-tabs>
				</el-aside>
				<el-main class="right">

					<div class="title">
						常用商品
					</div>
					<div class="offtenGoods">
						<ul>
							<li v-for="goods in offtenGoods" @click="addOrderList(goods)">
								<span>{{goods.goodsName}}</span>
								<span>￥{{goods.price}}元</span>
							</li>
						</ul>
					</div>
					<div class="goodsList">

						<el-tabs v-model="activeClass" @tab-click="handleClick">
							<el-tab-pane label="汉堡" name="first">
								<ul>
									<li v-for="goods in type1Goods" class="goodsItem" @click="addOrderList(goods)"
										:key="goods._id">
										<div class="itemLeft">
											<img :src="imgUrl+goods.goodsImg" alt="">
										</div>
										<div class="itemRight">
											<span>{{goods.goodsName}}</span>
											<span>￥{{goods.price}}元</span>
										</div>
									</li>
								</ul>
							</el-tab-pane>
							<el-tab-pane label="主食" name="second">
								<ul>
									<li v-for="goods in type2Goods" class="goodsItem" @click="addOrderList(goods)"
										:key="goods._id">
										<div class="itemLeft">
											<img :src="imgUrl+goods.goodsImg" alt="">
										</div>
										<div class="itemRight">
											<span>{{goods.goodsName}}</span>
											<span>￥{{goods.price}}元</span>
										</div>
									</li>
								</ul>
							</el-tab-pane>
							<el-tab-pane label="饮料" name="third">
								<ul>
									<li v-for="goods in type3Goods" class="goodsItem" @click="addOrderList(goods)"
										:key="goods._id">
										<div class="itemLeft">
											<img :src="imgUrl+goods.goodsImg" alt="">
										</div>
										<div class="itemRight">
											<span>{{goods.goodsName}}</span>
											<span>￥{{goods.price}}元</span>
										</div>
									</li>
								</ul>
							</el-tab-pane>

						</el-tabs>
					</div>

				</el-main>
			</el-container>
		</el-main>
	</el-container>

</template>

<script>
	import LeftNav from '../common/leftNav.vue'

	export default {
		//组件中路由守卫（导航守卫）
		beforeRouteEnter(to, from, next) {
			// 在渲染该组件的对应路由被验证前调用
			// 不能获取组件实例 `this` ！
			// 因为当守卫执行时，组件实例还没被创建！
			var token = localStorage.getItem("tokenID")
			if (token)
				next()
			else
				next({
					name: "Login"
				});
		},
		data() {
			return {
				activeName: 'first',
				activeClass: 'first',
				offtenGoods: [],
				type1Goods: [],
				type2Goods: [],
				type3Goods: [],
				totalCount: 0,
				totalMoney: 0,
				tableData: [],
				historyOrderList: []
			}
		},
		methods: {
			handleClick(tab, event) {
				console.log(tab, event);
			},
			//删除一种商品
			deleteRow(row) {
				// this.tableData.splice()
				console.log(row);
				let delIndex = -1;
				for (let i = 0; i < this.tableData.length; i++) {
					if (this.tableData[i].goodsName == row.goodsName) {
						delIndex = i;
						break;
					}
				}
				//删除一条索引记录
				this.tableData.splice(delIndex, 1);
				//计算价格和数量
				this.getTotal();
			},
			//计算总数和总价
			getTotal() {
				this.totalCount = 0;
				this.totalMoney = 0;
				this.tableData.forEach(e => {
					this.totalCount += e.count;
					this.totalMoney += e.count * e.price;
				})
			},
			// 添加到点餐临时数据
			addOrderList(row) {
				//先判断当前这个商品是否存在于左边的表中
				let result = this.tableData.filter(e => e.id == row._id);
				let isHave = result.length;
				if (isHave) {
					// this.$message("有数据")
					result[0].count++;
				} else {
					// this.$message("没数据")
					let newData = {
						id: row._id,
						goodsName: row.goodsName,
						count: 1,
						price: row.price
					}
					this.tableData.push(newData);
				}
				//计算价格和数量
				this.getTotal();
			},
			//清空点餐临时表、清空总数、清空总价
			clearData() {
				this.tableData = [],
					this.totalCount = 0,
					this.totalMoney = 0
			},
			//结账
			checkOut() {
				//判断是否有结账的必要
				if (this.tableData.length != 0) {

					//生成订单的详情
					let orderlist = [];
					for (let i = 0; i < this.tableData.length; i++) {
						orderlist.push({
							goodsName: this.tableData[i].goodsName,
							count: this.tableData[i].count,
							price: this.tableData[i].price
						})
					}
					//构造订单表的数据
					let newData = {
						tokenid: localStorage.getItem("tokenID"),
						username: localStorage.getItem("username"),
						orderlist: orderlist,
						creattime: Date.now(),
						orderstate: "nopay",
						ordertotal: this.totalMoney
					}
					//提交订单
					this.$http.post('/orderlistadd', newData).then(res => {
						console.log(res);

						//判断当前用户是否过期
						if (res.data.errCode == 1) {
							this.$message.info(res.data.errMsg);
							this.$router.push('/');
							return;
						}
						//清空已提交的商品并提示
						this.clearData();
						this.$message.success("订单已生成");
						this.getOrderList();
					}).catch(err => {
						this.$message.error("网络连接错误，请联系管理员");
					})
				} else {
					this.$message.info("请先选择要购买的商品");
				}
			},
			//查看所有购买的订单
			getOrderList() {
				let tokenid = localStorage.getItem("tokenID");
				let username = localStorage.getItem("username");

				this.$http.post("/orderlistget", {
					tokenid,
					username
				}).then(res => {
					console.log(res);
					this.historyOrderList = res.data.list;
				}).catch(err => {
					this.$message.error("网络异常，请联系管理员");
				})
			}
		},
		components: {
			"left-nav": LeftNav
		},
		created() {

			//经常购买的商品
			this.$http.post("/goodsofftenlist").then(res => {
				if (res.data.errCode == 0) {
					this.offtenGoods = res.data.list;
				} else {
					this.$message.info(res.data.errMsg);
				}
			}).catch(err => {
				this.$message.error("网络连接失败,请稍候再试！");
				this.$router.push('/');
			});
			//三种类型的商品
			this.$http.post("/goodslist").then(res => {
				// console.log(res);
				if (res.data.errCode == 0) {
					this.type1Goods = res.data.list.type1;
					this.type2Goods = res.data.list.type2;
					this.type3Goods = res.data.list.type3;
				} else {
					this.$message.info(res.data.errMsg);
				}
			}).catch(err => {
				this.$message.error("网络连接失败,请稍候再试！");
				this.$router.push('/');
			});
			//计算一下
			this.getTotal();
		},
		mounted() {
			//通过计算方式获得设备高度
			let ch = document.documentElement.clientHeight + "px";
			this.$set(document.querySelector('.left').style, "height", ch);
			this.$set(document.querySelector('.main').style, "height", ch);
			this.$set(document.querySelector('.right').style, "height", ch);

			//获取历史订单
			this.getOrderList();
		}

	}
</script>

<style scoped>
	.left {
		background-color: #0094ff;
		width: 85px !important;
		/* height: 720px; */
	}


	.main,
	.right {
		padding: 0px;
		/* height: 720px; */
	}

	.center {
		background-color: #fff;
		width: 400px !important;
	}

	.right {
		background-color: #eee;
		border-left: 1px solid #ccc;
	}


	.iconfont {
		font-size: 48px;
		color: #FFF;
		background-color: #f02550;
	}

	.title {
		background-color: #fff;
		padding: 10px;

	}

	.offtenGoods {
		display: flex;
	}

	.offtenGoods li {
		background-color: #fff;
		padding: 10px 0px;
		float: left;
		margin: 20px 0px 15px 10px;
		list-style: none;
		cursor: pointer;
	}

	.offtenGoods li span {
		padding: 0px 8px;
	}

	.offtenGoods li :last-child {
		color: #0094ff;
	}

	.goodsItem {
		display: flex;
		width: 23%;
		margin-left: 1%;
		float: left;
		background-color: #FFF;
		cursor: pointer;
	}

	.goodsItem .itemLeft {
		flex: 2;
		padding: 5px;
	}

	.goodsItem .itemLeft img {
		width: 100%;
	}

	.goodsItem .itemRight {
		flex: 3;
		padding: 5px;
	}

	.goodsItem .itemRight span {
		display: block;
	}

	.goodsItem .itemRight span:first-child {
		color: #a52a2a;
		font-weight: 800;
		margin-bottom: 20px;
	}

	.SummaryTotal {
		text-align: right;
		padding-right: 50px;
		margin-top: 10px;
	}

	.btns {
		text-align: center;
		margin-top: 30px;
	}

	.historyOrderList {
		list-style: none;
		font-size: 14px;
	}

	.historyOrderList li {
		margin: 10px;
	}

	.historyOrderList li div {
		display: flex;
		margin: 5px 0px;
		border: 1px solid #eee;
		padding: 5px;
	}

	.historyOrderList li div .orderid {
		flex: 3;
	}

	.historyOrderList li div .money {
		flex: 1;
		font-size: 14px;
		color: red;
	}

	.historyOrderList li table {
		width: 100%;
		font-size: 10px;
		border: 1px solid #eee;
	}

	.historyOrderList li table .row-title {
		width: 100%;
		background-color: #f8f8d9;
	}

	.historyOrderList li table .row-title th {
		width: 33%;
		text-align: center;
		padding: 5px;
	}

	.historyOrderList li table .row-cols td {
		width: 33%;
		text-align: center;
		padding: 5px;
	}
</style>
